<?php


namespace app\utils;

use app\msgapi\model\System;
use PHPMailer\PHPMailer\{PHPMailer, Exception};

class Mail
{
    private PHPMailer $PHPMailer;
    public function __construct(PHPMailer $PHPMailer)
    {
        $this->PHPMailer = $PHPMailer;// 默认不抛出外部异常
    }

    /**
     * 邮件发送
     * @param string $title 主题
     * @param string $content 内容
     * @param string|array $address 收件箱地址
     * @return bool
     * @throws UtilsException
     */
    function send(string $title, string $content, $address): bool
    {
        $email_config = System::getSys('email_config');
        if(!$address){
            $address = $email_config['inbox'];
        }
        if (is_string($address)) {
            $address = explode(',', $address);
        }
        try {
            //服务器设置
            $this->PHPMailer->SMTPDebug = 0;                      // SMTP::DEBUG_SERVER启用详细的调试输出
            $this->PHPMailer->isSMTP();                                      // 使用SMTP
            $this->PHPMailer->CharSet = 'UTF-8';                             // 使用UTF-8编码
            $this->PHPMailer->Host = $email_config['smtp'];            // 将SMTP服务器设置为通过
            $this->PHPMailer->SMTPAuth = true;                             // 启用SMTP身份验证
            $this->PHPMailer->Username = $email_config['loginname'];       // SMTP用户名
            $this->PHPMailer->Password = $email_config['password'];        // SMTP密码
            $this->PHPMailer->SMTPSecure = $email_config['encry'];           // 启用ssl加密
            $this->PHPMailer->Port = $email_config['port'];            // 要连接的TCP端口，腾讯企业邮箱：465

            $this->PHPMailer->setFrom($email_config['loginname'], $email_config['sender']);//发件人
            foreach ($address as $v){
                $this->PHPMailer->addAddress($v);    // 添加收件人,名称是可选的
            }
            //$mail->addReplyTo('info@example.com', 'Information');       // 添加一个“回复”地址。
            //$mail->addCC('cc@example.com');                             // 抄送地址。
            //$mail->addBCC('bcc@example.com');                           // 添加“密件抄送”地址
            // 附件
            //$mail->addAttachment('/var/tmp/file.tar.gz');         // 添加附件
            //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // 可选名称
            // 内容
            $this->PHPMailer->isHTML(true);                   // 将电子邮件格式设置为HTML
            $this->PHPMailer->Subject = '会话存档系统-' . $title;               // 这是主题
            $this->PHPMailer->Body = $content;             // 这是HTML邮件正文
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';// 这是非HTML邮件客户端的纯文本正文
            $this->PHPMailer->setLanguage('zh_cn');           // 错误信息显示中文

            $this->PHPMailer->send();  // 消息已发送
            return true;
        } catch (Exception $e) {
            throw new UtilsException($this->PHPMailer->ErrorInfo);
        }
    }
}